#include "IRInputFilter.h"
#include <opencv2/imgproc/imgproc.hpp>

IRInputFilter::IRInputFilter(int width, int height, int fps, bool mirror) : width(width), height(height), InputFilter()
{
	mapMode.nXRes = width;
	mapMode.nYRes = height;
	mapMode.nFPS = fps;

	ucharOutput = false;
	initialized = false;

	node = &ir;
	ir.Create(context);
	ir.SetMapOutputMode(mapMode);
	ir.GetMirrorCap().SetMirror(mirror);

	context.StartGeneratingAll();
}


IRInputFilter::~IRInputFilter(void)
{
}

void IRInputFilter::Process()
{
	if (!initialized)
	{
		initialized = true;

		if (ucharOutput)
		{
			outputs[0] = cv::Mat(height, width, CV_8UC1);
		}
		else
		{
			outputs[0] = cv::Mat(height, width, CV_16UC1);
		}
	}

	if (ucharOutput)
	{
		const XnIRPixel *inputPtr = ir.GetIRMap();

		ushort minValue = 0xffff;
		ushort maxValue = 0;

		for (int i = 0; i < height; ++i)
		{
			for (int j = 0; j < width; ++j)
			{
				ushort v = inputPtr[i * width + j];
				minValue = MIN(minValue, v);
				maxValue = MAX(maxValue, v);
			}
		}

		int brekpoint = 0;

		for (int i = 0; i < height; ++i)
		{
			uchar *p = outputs[0].ptr<uchar>(i);
			for (int j = 0; j < width; ++j)
			{
				ushort val = inputPtr[i * width + j];
				//uchar newVal = (val - minValue) * (maxValue - minValue) * 0xff / 0xffff;
				p[j] = MIN(0xff, val / 4);
			}
		}
	}
	else
	{
		std::memcpy(outputs[0].data, ir.GetIRMap(), width * height * 2);
	}
}
